<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-row>
          <el-col :span="4">
            <el-button type="success" round size="large" @click="showAdd">新增</el-button>
          </el-col>
          <el-col :span="4"></el-col>
          <el-col :span="3">
            <el-select
                v-model="condition.status"
                clearable
                placeholder="选择是否上架"
                style="width: 150px"
                :empty-values="[null, undefined]"
                :value-on-clear="null"
                @change="getAll(1)"
            >
              <el-option label="上架" :value="1"/>
              <el-option label="不上架" :value="0"/>
            </el-select>
          </el-col>
          <el-col :span="1"></el-col>
          <el-col :span="3">
            <el-input v-model="condition.name" style="width: 160px" @input="getAll(1)" placeholder="请输入分类名称"/>
          </el-col>
          <el-col :span="1"></el-col>
          <el-col :span="3">
            <el-select
                v-model="condition.parentId"
                clearable
                placeholder="选择一级分类标签"
                style="width: 160px"
                :empty-values="[null, undefined]"
                :value-on-clear="null"
                @change="getAll(1)"
            >
              <el-option
                  v-for="(item, index) in parentInfo"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="1"></el-col>
          <el-col :span="4">

          </el-col>
        </el-row>
      </div>
    </template>
    <el-table :data="categoryInfo.list" style="width: 100%">
      <el-table-column prop="id" label="id"/>
      <el-table-column label="分类图片">
        <template #default="scope">
          <el-avatar shape="square" size="large"
                     :src="imagesBasePath + '/file/images/' + scope.row.pic"/>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="分类名称"/>
      <el-table-column prop="dscp" label="分类描述"/>
      <el-table-column prop="parent.name" label="父分类"/>
      <el-table-column label="推荐">
        <template #default="scope">
          <el-tag v-if="scope.row.recom === 1" type="success">推荐</el-tag>
          <el-tag v-else type="info">不推荐</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否上架">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">上架</el-tag>
          <el-tag v-else type="info">不上架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="showUpdate(scope.row.id)">编辑</el-button>
          <el-popconfirm title="你确定要删除改分类吗？" confirm-button-text="确认" cancel-button-text="取消"
                         @confirm="delInfo(scope.row.id)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-row class="row-bg" justify="space-evenly">
        <el-col :span="6">
          <el-pagination layout="prev, pager, next" :total="categoryInfo.total" :page-size="categoryInfo.pageSize"
                         @current-change="getAll"/>
        </el-col>
      </el-row>
    </template>
  </el-card>


  <!-- START 新增对话框 -->
  <el-dialog v-model="addVisible" title="新增分类" align-center style="width: 300px">
    <el-form :model="addInfoForm">
      <el-form-item label="名称" style="width: 250px">
        <el-input v-model="addInfoForm.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="描述" style="width: 250px">
        <el-input v-model="addInfoForm.dscp" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="上级分类">
        <el-select
            v-model="addInfoForm.parentId"
            clearable
            placeholder="选择分类标签"
            style="width: 160px"
            :empty-values="[0]"
            :value-on-clear=0
        >
          <el-option label="一级分类" :value= 0 />
          <el-option
              v-for="(item, index) in parentInfo"
              :key="index"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐">
        <el-radio-group v-model="addInfoForm.recom">
          <el-radio :value="0" size="large">不推荐</el-radio>
          <el-radio :value="1" size="large">推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-radio-group v-model="addInfoForm.status">
          <el-radio :value="0" size="large">不上架</el-radio>
          <el-radio :value="1" size="large">上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分类图片">
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="handleUpload"
                   :before-upload="addCategoryUpload">
          <img v-if="addInfoForm.pic" :src="imagesBasePath + '/file/images/' + addInfoForm.pic" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">提交</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- END 新增对话框 -->


  <!-- START 修改对话框 -->
  <el-dialog v-model="updateVisible" title="更新分类" align-center style="width: 300px">
    <el-form :model="updateInfoForm">
      <el-form-item label="名称" style="width: 250px">
        <el-input v-model="updateInfoForm.name" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="描述" style="width: 250px">
        <el-input v-model="updateInfoForm.dscp" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="上级分类">
        <el-select
            v-model="updateInfoForm.parentId"

            placeholder="选择分类标签"
            style="width: 160px"
        >
          <el-option label="一级分类" :value= 0 />
          <el-option
              v-for="(item, index) in parentInfo"
              :key="index"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否推荐">
        <el-radio-group v-model="updateInfoForm.recom">
          <el-radio :value="0" size="large">不推荐</el-radio>
          <el-radio :value="1" size="large">推荐</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架">
        <el-radio-group v-model="updateInfoForm.status">
          <el-radio :value="0" size="large">不上架</el-radio>
          <el-radio :value="1" size="large">上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分类图片">
        <el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="handleUploadUpdate"
                   :before-upload="addCategoryUpload">
          <img v-if="updateInfoForm.pic" :src="imagesBasePath + '/file/images/' + updateInfoForm.pic" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpdate">提交</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- END 修改对话框 -->
</template>

<script setup>

// 全部信息
import {ref} from "vue";
import categoryApi from "@/api/categoryApi.js";
import fileApi from "@/api/FileApi.js";
import {ElMessage} from "element-plus";

// 图片基本地址
const imagesBasePath = ref(import.meta.env.VITE_SERVER_ADDR)
// 分页信息
const categoryInfo = ref({
  list: [],
  total: 0,
  pageSize: 5,
  pageNum:1
})
// 搜索相关信息
const condition = ref({
  name: null,
  parentId: null,
  status: null
})
// 父分类相关内容
const parentInfo = ref([])
// 新增弹出层
const addVisible = ref(false)
// 编辑弹出层
const updateVisible = ref(false)

// 新增信息
const addInfoForm = ref({
  name:'',
  dscp:'',
  pic:'',
  parentId:0,
  recom:1,
  status:1
})
// 修改信息
const updateInfoForm = ref({
  name:'',
  dscp:'',
  pic:'',
  parentId:0,
  recom:1,
  status:1
})

// ================================

// 获得全部的分类信息
const getAll = (pageNum) => {
  categoryApi.selectByPage(condition.value, pageNum, 5)
      .then(resp => {
        categoryInfo.value = resp.data
      })
}
// 获取全部父分类信息
const getParentInfo = () => {
  categoryApi.getParentInfo(0)
      .then(resp => {
        parentInfo.value = resp.data;
      })
}

// 新增上传的请求
const handleUpload = (file) => {
  let fd = new FormData();
  fd.append("file", file.file);
  fileApi.imagesUpload(fd)
      .then(resp => {
        if (resp.code === 10000) {
          addInfoForm.value.pic = resp.data;
        }
      });
}

// 更新上传的请求
const handleUploadUpdate = (file) => {
  let fd = new FormData();
  fd.append("file", file.file);
  fileApi.imagesUpload(fd)
      .then(resp => {
        if (resp.code === 10000) {
          updateInfoForm.value.pic = resp.data;
        }
      });
}

// 新增之前的钩子函数
const addCategoryUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式要是JPG')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不要超过2MB!')
    return false
  }
  return true
}

// 打开新增弹出层
const showAdd = () => {
  getParentInfo();
  addVisible.value = true;
}

// 打开更新弹出层
const showUpdate = (id) => {
  getParentInfo()
  categoryApi.selectById(id)
      .then(resp => {
        if (resp.code === 10000) {
          updateInfoForm.value = resp.data
          updateVisible.value = true
        }
      })
}

// 提交新增
const submitAdd = () => {
  categoryApi.insert(addInfoForm.value)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          getAll(categoryInfo.value.pageNum)
          getParentInfo()
          addVisible.value = false
          addInfoForm.value = {
            name:'',
            dscp:'',
            pic:'',
            parentId:0,
            recom:1,
            status:1
          }
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 提交更新
const submitUpdate = () => {
  categoryApi.update(updateInfoForm.value)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          getAll(categoryInfo.value.pageNum)
          getParentInfo()
          updateVisible.value = false
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

// 删除商品分类
const delInfo = (id) => {
  categoryApi.delete(id)
      .then(resp => {
        if (resp.code === 10000) {
          ElMessage.success(resp.msg)
          getAll(categoryInfo.value.pageNum)
          getParentInfo()
        } else {
          ElMessage.error(resp.msg)
        }
      })
}

getAll(1)
getParentInfo()
</script>

<style scoped>

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.el-card__header {
  padding-top: 5px;
  padding-bottom: 2px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>